<template>
  <!-- 战败车型 -->
  <div>
    <TopFilter
      ref="TopFilter"
      :list="topFilterList"
      :cols="3"
      labelWidth="100"
      @filterChange="changeHandle"
      @onCollapse="collapseHandle"
    ></TopFilter>

    <FilterTable
      ref="table"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'records'"
      :rowstyles="rowstyles"
      :cellstyles="cellstyles"
      :isSelectColumn='false'
      :onColumnsChange="columns => this.columns = columns"
      :onSyncTableData="DataHandle"
      columnsRef="potenCus_customer_returnSales_sales_01"
    >
      <template slot="controls">
        <el-button type="text" disabled>红色行代表逾期</el-button>
      </template>
    </FilterTable>
    <BaseDialog
      :visible.sync="visible"
      :title="dialogTitle"
      width=50%
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <salesModel :type="handleType" :rowData="formData" @close="closeHandler" />
    </BaseDialog>
    <!-- 明细页面 -->
    <Drawer
      :visible.sync="visible_custs"
      title="客户信息"
      :width="1000"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"

    >
      <!-- <div class="father">
        <div class="son">
          <el-button size="small" :disabled="formData.actionId?false:true" type="primary" @click="followUp">跟进</el-button>
          <el-button size="small" type="primary" @click="continueBuy">续购</el-button>
        </div>
      </div> -->
      <custsDetail :type="handleType" :rowData="formData_custs" @close="closeHandler_custs" />
    </Drawer>

  </div>
</template>

<script>
import { getReturnSalesList, getReturnSalesById } from '@/api/potenCus/customer/returnSales';
import { dictionary } from '@/utils/dictMixin';
import { authority } from '@/utils/authMixin';
import { formatDates } from '@/utils/validate';
import { getDataType } from '@/assets/js/auth';
import moment from 'moment';
import salesModel from './salesModel';
import custsDetail from '../../../basePlate/cust1Manage/custsDetail';

export default {
  name: 'Sales',
  mixins: [dictionary, authority],
  components: {
    salesModel,
    custsDetail
  },
  props: {
    isComplete: {
      type: Number,
      default: 10041002
    },
    rowData: {
      type: Object,
      default: () => ({})
    },
    searchData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      dataType: getDataType('dataType'),
      topFilterList: this.createTopFilters(),
      fetchParams: {
        isComplete: this.isComplete,
        planActionDate: this.searchData.planActionDate || undefined,
        planActionDateEnd: this.searchData.planActionDateEnd || undefined,
        isOverdue: this.searchData.isOverdue || undefined
      },
      visible: false,
      visible_custs: false,
      formData: {},
      formData_custs: {},
      dialogTitle: '',
      fetchApi: getReturnSalesList,
      columns: this.createTableColumns(),
      handleType: '',
      conf:{ edit: '编辑', show: '明细' },
      rowstyles: [],
      cellstyles: [],
      page: {
        pageNum: 1,
        currentPage: 1,
        pageSize: 20,
        limit: 20
      }
    };
  },
  created() {
    this.init()
  },
  methods: {
    init(){
      console.log("this.rowData", this.rowData)
      console.log("回访是否完成", this.isComplete)
      console.log(this.dataType)
      if(this.isComplete == 10041003){
        this.topFilterList.splice(2,0,{
          type: 'SELECT',
          label: '是否完成',
          fieldName: 'isAll',
          placeholder: '请选择',
          itemList: this.createDictList('1004')
        })
      }
    },
    createTopFilters() {
      return [
        {
          type: 'INPUT',
          label: '关键字',
          fieldName: 'customerNameOrPhone',
          placeholder: '客户名称/手机号'
        },
        {
          type: 'RANGE_DATE',
          label: '计划跟进时间',
          fieldName: 'planActionDate|planActionDateEnd',
          placeholder: '请输入'
        },
        {
          type: 'SELECT',
          label: '是否逾期',
          fieldName: 'isOverdue',
          placeholder: '请选择',
          itemList: this.createDictList('7044')
        },
      ];
    },
    createTableColumns() {
      return [
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <multiuse-button size="mini" type="text" disabled={props.row.isComplete==10041001?true:false} onClick={() => this.editHandle(props.row)}>
                  回访
                </multiuse-button>
                <el-divider direction="vertical" />
                <multiuse-button size="mini" type="text" onClick={() => this.showHandle(props.row)}>
                  明细
                </multiuse-button>
              </div>
            );
          }
        },
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '客户名称',
          dataIndex: 'customerName',
          filter: true,
          align: 'center',
          filterType: 'input',
        },
        {
          title: '客户类型',
          dataIndex: 'customerType',
          sorter: true,
          filter: true,
          align: 'center',
          filterType: 'checkbox',
          filterItems: this.createDictList('1523'),
          render: props => {
            return <span>{this.createDictText(props.row.customerType, '1523')}</span>;
          }
        },
        {
          title: '联系人姓名',
          dataIndex: 'contactName',
          filter: true,
          align: 'center',
          filterType: 'input',
        },
        {
          title: '性别',
          dataIndex: 'gender',
          align: 'center',
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1002'),
          render: props => {
            return <span>{this.createDictText(props.row.gender, '1002')}</span>;
          }
        },
        {
          title: '手机号码',
          dataIndex: 'mobilePhone',
          align: 'center',
          filter: true,
          filterType: 'input',
        },
        {
          title: '跟进备注',
          dataIndex: 'taskName',
          align: 'center',
          filter: true,
          filterType: 'input',
        },
        {
          title: '计划跟进时间',
          dataIndex: 'planActionDate',
          sorter: true,
          align: 'center',
          // filterType: 'date-range',
          // dateFormat: 'yyyy-MM-dd'
        },
        {
          title: '实际跟进时间',
          dataIndex: 'factActionDate',
          sorter: true,
          align: 'center',
          // filterType: 'date-range',
          // dateFormat: 'yyyy-MM-dd'
        },
        {
          title: '跟进方式',
          dataIndex: 'factActionModeName',
          align: 'center',
          sorter: true,
          filterType: 'input',
          // filterItems: this.createDictList('1516'),
          // render: props => {
          //   return <span>{this.createDictText(props.row.factActionMode, '1516')}</span>;
          // }
        },
        {
          title: '是否逾期',
          dataIndex: 'isOverdue',
          align: 'center',
          filterType: 'checkbox',
          filterItems: this.createDictList('7044'),
          render: props => {
            return <span>{this.createDictText(props.row.isOverdue, '7044')}</span>;
          }
        },
        {
          title: '逾期时长',
          dataIndex: 'overdueTime',
          align: 'center',
          filterType: 'input'
        },
        {
          title: '是否完成',
          dataIndex: 'isComplete',
          align: 'center',
          filterType: 'checkbox',
          filterItems: this.createDictList('1004'),
          render: props => {
            return <span>{this.createDictText(props.row.isComplete, '1004')}</span>;
          }
        },
        {
          title: '所属顾问',
          dataIndex: 'consultantName',
          filterType: 'input',
        },
        {
          title: '本次跟进情形',
          dataIndex: 'actionedScene',
          filter: true,
          filterType: 'input',
        },
      ];
    },
    editHandle(row) {
      console.log('编辑', row);
      this.handleType = 'edit';
      this.formData = row;
      this.showHandler();
    },
    async showHandle(row) {
      console.log('明细', row);
      this.handleType = 'show';
      // TODO
      const res = await getReturnSalesById(row.actionId);
      console.log('id回访明细', res);
      let newRow
      if(res.data){
        newRow = {
          ...res.data,
          potentialCustomersId:  row.potentialCustomersId,
          potentialCustomerName: res.data.customerName,
          potentialCustomerPhone: res.data.mobilePhone,
          customerName: res.data.customerName,
          employeeName: res.data.telemarketingName,
          customerNo: res.data.potentialCustomerNo,
          consultant: res.data.consultant,
          vehicleUse: res.data.buyCarUse,
          ctCode: res.data.ctCode,
          certificateNo: res.data.certificateNo,
          soStatus: 14041001,   // 订单状态:未提交
          clueType: 70241002,   // 后台确定写死
          isShowCustomer: 10041001, // 基盘是否可操作联系人
        }
      }
      this.formData_custs = newRow;
      this.visible_custs = true;
      console.log(this.formData_custs,this.handleType,"回访跳转携带formData")
      // this.showHandler();
    },
    showHandler() {
      this.dialogTitle = `销售回访${this.conf[this.handleType]}`;
      this.visible = true;
    },
    changeHandle(val) {
      // console.log(val)
      if (this.isComplete) {
        this.fetchParams = Object.assign({isComplete: this.isComplete}, val)
      } else {
        this.fetchParams = Object.assign({}, val);
      }
      // console.log(this.fetchParams)
    },
    DataHandle(data, isOverdue){
      // console.log(data, isOverdue)
      if(!data.length) return;
      // 当天日期
      let currentDate = moment().format('YYYY-MM-DD')
      data.forEach(x=>{
        if(x.isOverdue == 70441001 && x.isComplete == 10041002) {
          this.rowstyles.push({ row:x, styles:{background: '#FFCCCC'} })
        }
        else if(x.planActionDate !='' && x.isComplete == 10041002) {
          if(moment(x.planActionDate).format('YYYY-MM-DD') == currentDate) {
            this.rowstyles.push({ row:x, styles:{background: '#FAFF69'} })
          }
        }
      })
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    closeHandler(val, type) {
      this.visible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    closeHandler_custs(val, type) {
      this.visible_custs = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },

  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
    // 首页进入时
    if (this.searchData.planActionDate) {
      this.topFilterList.find(item => item.fieldName === 'planActionDate|planActionDateEnd').initialValue=[
        this.searchData.planActionDate,this.searchData.planActionDateEnd
      ]
      if (this.searchData.isOverdue) {
        this.topFilterList.find(item => item.fieldName === 'isOverdue').initialValue=this.searchData.isOverdue
      }
      setTimeout(() => {
        this.$refs.TopFilter.SUBMIT_FORM()
      },400);
    }
  },
};
</script>

<style lang="less" scoped>
.father{
  width: 380px;
  height: auto;
  position: relative;
  float: right;
}
.son{
  position: absolute;
  top: -5px;
  right: 10px;
  z-index: 2;
}
</style>
